package org.ruoyi.chat.service.chat.impl;

import io.modelcontextprotocol.client.McpSyncClient;
import lombok.extern.slf4j.Slf4j;
import org.ruoyi.chat.config.ChatConfig;
import org.ruoyi.chat.enums.ChatModeType;
import org.ruoyi.chat.listener.SSEEventSourceListener;
import org.ruoyi.chat.service.chat.IChatService;
import org.ruoyi.common.chat.entity.chat.ChatCompletion;
import org.ruoyi.common.chat.entity.chat.Message;
import org.ruoyi.common.chat.openai.OpenAiStreamClient;
import org.ruoyi.common.chat.request.ChatRequest;
import org.ruoyi.domain.vo.ChatModelVo;
import org.ruoyi.service.IChatModelService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ageer
 */
@Service
@Slf4j
public class DashscopeServiceImpl implements IChatService {

    private final ChatClient chatClient;
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();
    @Autowired
    private IChatModelService chatModelService;
    @Value("${spring.ai.mcp.client.enabled}")
    private Boolean enabled;

    public DashscopeServiceImpl(ChatClient.Builder chatClientBuilder, List<McpSyncClient> mcpSyncClients) {
        this.chatClient = chatClientBuilder
                .defaultOptions(
                        OpenAiChatOptions.builder().model("gpt-4o-mini").build())
                .defaultTools(new SyncMcpToolCallbackProvider(mcpSyncClients))
                .build();
    }

    @Override
    public SseEmitter chat(ChatRequest chatRequest, SseEmitter emitter) {
        ChatModelVo chatModelVo = chatModelService.selectModelByName(chatRequest.getModel());
        OpenAiStreamClient openAiStreamClient = ChatConfig.createDashScopeClient(chatModelVo.getApiHost(), chatModelVo.getApiKey());
        List<Message> messages = chatRequest.getMessages();
        if (enabled) {
            String toolString = mcpChat(chatRequest.getPrompt());
            Message userMessage = Message.builder().content("工具返回信息：" + toolString).role(Message.Role.USER).build();
            messages.add(userMessage);
        }
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiJzeXNfdXNlcjoxIiwicm5TdHIiOiJQNWs5NGtxOEdUaHN1M3dlZFpqcUlxWm9Dc0xUbm9BOSIsInRlbmFudElkIjoiMDAwMDAiLCJ1c2VySWQiOjF9.Fgr-EtGEiPi3FUhgtPjLdJwjk_UmOnB6i4PSgzXJXVo";

        SSEEventSourceListener listener = new SSEEventSourceListener(emitter, chatRequest.getUserId(), chatRequest.getSessionId(), token);
        ChatCompletion completion = ChatCompletion
                .builder()
                .messages(messages)
                .model(chatRequest.getModel())
                .stream(true)
                .build();
        openAiStreamClient.streamChatCompletion(completion, listener);
        return emitter;
    }

    @Override
    public SseEmitter chat(ChatRequest chatRequest, SseEmitter emitter, WebSocketSession webSocketSession) {
        ChatModelVo chatModelVo = chatModelService.selectModelByName(chatRequest.getModel());
        if (Objects.isNull(chatModelVo)) {
            return emitter;
        }

        // ✅ 使用 createDashScopeClient 创建适配百炼的客户端
        OpenAiStreamClient openAiStreamClient = ChatConfig.createDashScopeClient(chatModelVo.getApiHost(), chatModelVo.getApiKey());

        List<Message> messages = chatRequest.getMessages();
        if (enabled) {
            String toolString = mcpChat(chatRequest.getPrompt());
            Message userMessage = Message.builder()
                    .content("工具返回信息：" + toolString)
                    .role(Message.Role.USER)
                    .build();
            messages.add(userMessage);
        }

        String token = chatRequest.getToken();

        // ✅ 使用 WebSocketSession 构造监听器
        SSEEventSourceListener listener = new SSEEventSourceListener(emitter, chatRequest.getUserId(), chatRequest.getSessionId(), token, webSocketSession);

        // ✅ 构造 ChatCompletion 请求参数
        ChatCompletion completion = ChatCompletion.builder()
                .messages(messages)
                .model(chatModelVo.getModelName())
                .temperature(0.2)
                .topP(1.0)
                .maxTokens(2048)
                .stream(true)
                .build();

        // ✅ 调用 DashScope 专用的流式接口
        openAiStreamClient.streamChatCompletion(completion, listener);
        return emitter;
    }

    public String mcpChat(String prompt) {
        return this.chatClient.prompt(prompt).call().content();
    }

    @Override
    public String getCategory() {
        return ChatModeType.CHAT.getCode();
    }

}
